(() => {
  try {
    let timer = null;
    const urls = new Set();
    const collect = (u) => {
      try {
        if (!u) return;
        const s = String(u);
        if (/^\/\//.test(s)) return; // ignore protocol-relative to avoid duplicates
        const ok = /\.(mp4|mov|webm)(\b|\?|#)/i.test(s) || /\.m3u8(\b|\?|#)/i.test(s);
        if (!ok) return;
        urls.add(s);
      } catch {}
    };
    const pump = () => {
      try {
        const ev = new CustomEvent('xhsd-net-urls', { detail: JSON.stringify(Array.from(urls)) });
        window.dispatchEvent(ev);
      } catch {}
    };
    // hook when asked to start
    const start = (ms) => {
      try {
        // scan existing performance entries immediately
        try { (performance.getEntriesByType('resource')||[]).forEach((e)=>collect(e.name)); } catch {}
        const ofetch = window.fetch;
        window.fetch = function(...args) {
          try { if (args && args[0]) collect(args[0].url || args[0]); } catch {}
          return ofetch.apply(this, args);
        };
        const OXHR = window.XMLHttpRequest;
        function NXHR() {
          const xhr = new OXHR();
          const oopen = xhr.open;
          xhr.open = function(m, u, ...rest) { try { collect(u); } catch {} return oopen.call(this, m, u, ...rest); };
          return xhr;
        }
        window.XMLHttpRequest = NXHR;
        clearTimeout(timer);
        timer = setTimeout(pump, Math.max(200, ms|0));
      } catch { pump(); }
    };
    window.addEventListener('xhsd-start-net-tap', (e) => {
      const ms = parseInt(e && e.detail, 10) || 1200;
      start(ms);
    });
  } catch (e) {
    try { const ev = new CustomEvent('xhsd-net-urls', { detail: JSON.stringify([]) }); window.dispatchEvent(ev); } catch {}
  }
})();
